/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import service.Audio;
import service.Connection;
import service.ConnectionFacadeREST;
import service.Photo;
import service.PhotoCollection;
import service.Planet;
import service.PlanetFacadeREST;
import service.Universe;
import service.UniverseFacadeREST;
import service.Video;


/**
 *
 * @author andrew
 */
@WebServlet(name = "deletePlanetServlet", urlPatterns = {"/deletePlanetServlet"})
public class deletePlanetServlet extends HttpServlet {

    @EJB
    private PlanetFacadeREST planetManager;
    
    @EJB
    private UniverseFacadeREST universeManager;
    
    @EJB
    private ConnectionFacadeREST connectionManager;
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //HttpSession session = request.getSession();
        // check if session is expired
        HttpSession session = request.getSession();// don't create if it doesn't exist
//        if(session != null && !session.isNew()) {} 
//        else {
//            response.sendRedirect("/home.jsp");
//        }
        
        Integer idUniverse = (Integer) session.getAttribute("idUniverse");
        
        String idPlanetString = request.getParameter("p");
        int idPlanet = Integer.parseInt(idPlanetString);
        
        // cancellazione immagini associate al pianeta nel filesystem
        Planet planet = planetManager.find(idPlanet);
        
        Collection<PhotoCollection> collPhotoColl = planet.getPhotoCollectionCollection();
        
        Iterator itCollPhotoColl = collPhotoColl.iterator();
        while(itCollPhotoColl.hasNext()){
            PhotoCollection c = (PhotoCollection) itCollPhotoColl.next();
            Collection<Photo> collPhoto = c.getPhotoCollection();
            Iterator itCollPhoto = collPhoto.iterator();
            while(itCollPhoto.hasNext()){
               Photo p = (Photo) itCollPhoto.next();
               
               // estrazione nome immagine al path
               String nameFileImg = p.getPathPhoto().substring(p.getPathPhoto().lastIndexOf("/")+1);
               // estrazione nome thumb
               String nameFileImgThumb = nameFileImg.substring(0,nameFileImg.lastIndexOf(".")) + "_thumb.jpg";
               
               // cancella immagine
               deleteFile(request.getServletContext().getRealPath("/")+"Universes/"+idUniverse+"/image/"+nameFileImg);
               // cancella thumb associata
               deleteFile(request.getServletContext().getRealPath("/")+"Universes/"+idUniverse+"/image/"+nameFileImgThumb);

            }
        }
        
        
        // cancellazione video associato al pianeta nel filesystem, se esiste
        Collection<Video> collVideo = planet.getVideoCollection();
        if(!collVideo.isEmpty()){
            Iterator itVideo = collVideo.iterator();
            while(itVideo.hasNext()){
                Video v = (Video) itVideo.next();
                String nameFileVideo = v.getPathVideo().substring(v.getPathVideo().lastIndexOf("/")+1);
                
                // cancellazione video
                deleteFile(request.getServletContext().getRealPath("/")+"Universes/"+idUniverse+"/video/"+nameFileVideo);
            }
        }
                
        // cancellazione audio associato al pianeta nel filesystem, se esiste
        Collection<Audio> collAudio = planet.getAudioCollection();
        if(!collAudio.isEmpty()){
            Iterator itAudio = collAudio.iterator();
            while(itAudio.hasNext()){
                Audio a = (Audio) itAudio.next();
                String nameFileAudio = a.getPathAudio().substring(a.getPathAudio().lastIndexOf("/")+1);
                
                // cancellazione audio
                deleteFile(request.getServletContext().getRealPath("/")+"Universes/"+idUniverse+"/audio/"+nameFileAudio);
            }
        }
        
        // cancellazione delle connessioni in cui "destinationPlanet" ha id del pianeta cancellato
        Universe universe = universeManager.find(idUniverse);
        Collection<Planet> collPlanet = universe.getPlanetCollection();
        Iterator iterator = collPlanet.iterator();
        while (iterator.hasNext()) {
            Planet p = (Planet) iterator.next();
            Collection<Connection> collConn = p.getConnectionCollection();
            Iterator<Connection> itConn = collConn.iterator();
            while(itConn.hasNext()){
                Connection c = itConn.next();
                if(c.getDestinationPlanet() == idPlanet){
                    // rimovo dalla lista
                    itConn.remove();
                    connectionManager.remove(c);
                    
                }
            }
            p.setConnectionCollection(collConn);
            planetManager.edit(p);
        }
        
        
        // cancellazione sulle liste e sul db
        
        universe = universeManager.find(idUniverse);
        collPlanet = universe.getPlanetCollection();
        iterator = collPlanet.iterator();
        while (iterator.hasNext()) {
            Planet p = (Planet) iterator.next();
            if(p.getIdPlanet() == planet.getIdPlanet()){
                iterator.remove();
            }
        }
        
        universe.setPlanetCollection(collPlanet);
        universeManager.edit(universe);
        
        planetManager.remove(planet);
        
        
        
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
    
    private static void deleteFile(String nameFile){
        try{
            File file = new File(nameFile);
            if(file.delete()){
                System.out.println(file.getName() + " is deleted!");
            }else{
    		System.out.println("Delete operation is failed.");
            }
    	}catch(Exception e){}
    }
}
